package cn.dlc.com.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class MyFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    // 是否开启过滤器，返回true表示开启
    @Override
    public boolean shouldFilter() {
        // 获取当前请求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        // 获取当前请求
        HttpServletRequest request = requestContext.getRequest();
        String token = request.getParameter("token");
        System.out.println("token : " + token);
        if("1".equals(token)) {
            return true;
        } else{
            return false;
        }
    }

    @Override
    public Object run() throws ZuulException {

        // 获取当前请求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        // 获取当前请求
        HttpServletRequest request = requestContext.getRequest();
        //
        String token = request.getParameter("token");
        if(token == null) {
            // 拦截请求
            requestContext.setSendZuulResponse(false);
            //
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }

        System.out.println("run.......");

        // 返回值为null表示正常
        return null;
    }
}
